package com.sdry.web.filter;

import com.sdry.utils.ResponseUtil;
import com.sdry.web.controller.cb.ReportFormController;
import net.sf.json.JSONObject;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        /*ModelAndView modelAndView = new ModelAndView();
        //将错误信息传到页面
        modelAndView.addObject("message","未知错误");
        //指向错误页面
        modelAndView.setViewName("cb/error");
        return modelAndView;*/

        Logger logger = LogManager.getLogger(ReportFormController.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("data", null);
        jsonObject.put("count", 0);


        logger.error("服务器出错", ex);



        jsonObject.put("message", "查询数据为空");

        //如果是ajax请求，就返回一个json格式的出错提示信息
        if (request.getHeader("X-Requested-With") != null) {
            try {
                ResponseUtil.write(response, jsonObject);
                response.getWriter().println("服务器出错了");
            } catch (Exception e) {
                logger.error("服务器失败时发送错误提示信息失败", e);
            }
            //返回一个空的ModelAndView表示已经手动生成响应
            //return null表示使用默认的处理方式，等于没处理
            return new ModelAndView("cb/error");
        } else {
            return new ModelAndView("cb/error");
        }
    }
}
